#include <stdio.h>
#include <stdbool.h>
#define Size 3
//初始化棋盘
void InitBoard(char (*Board)[Size])
{
    for(int i = 0;i < Size;i++)
    {
        for(int j = 0;j < Size;j++)
        {
            Board[i][j] = ' ';
        }
    }
}

void PrintBoard(char (*Board)[Size])
{
    for(int i =0;i < Size;i++)
    {
        for(int j = 0;j < Size;j++)
        {
            printf(" %c",Board[i][j]);
            if(j < Size - 1)
                printf(" |");
        }
        printf("\n");
        if(i < Size - 1)
            printf("———|———|———\n");
    }
}

//穷举
bool CheckIsWin(char (*Board)[Size],char player)
{
    for(int i = 0;i < Size;i++)
    {
        if(Board[i][0] == player 
            && Board[i][1] == player 
            && Board[i][2] == player)
        {
            return true;
        }
        if(Board[0][i] == player 
            && Board[1][i] == player 
            && Board[2][i] == player)
        {
            return true;
        }
    }
    if(Board[0][0] == player 
        && Board[1][1] == player 
        && Board[2][2] == player)
    {
        return true;
    }
    if(Board[0][2] == player 
        && Board[1][1] == player 
        && Board[2][0] == player)
    {
        return true;
    }
    return false;
}

bool CheckIsDrawn(char (*Board)[Size])
{
    for(int i =0;i < Size;i++)
    {
        for(int j = 0;j < Size;j++)
        {
            if(Board[i][j] == ' ')
            {
                return false;
            }
        }
    }
    return true;
}

bool MakeMove(char (*Board)[Size],int row,int col,char player)
{
    if(row < 0 || row >= Size || col < 0 || col >= Size)
    {
        printf("非法位置，请重新输入！\n");
        return false;
    }
    if(Board[row][col] != ' ')
    {
        printf("位置非空！请重新输入！\n");
        return false;
    }

    Board[row][col] = player;
    return true;
}   


int main()
{
    //定义棋盘
    char Board[Size][Size] = {0};
    InitBoard(Board);
    char player = 'X';
    while(1)
    {
        PrintBoard(Board);
        int row,col;
        printf("请|%c|选手下棋：\n",player);
        printf("请输入落棋的位置：");
        scanf("%d %d",&row,&col);
        if(MakeMove(Board,row-1,col-1,player) == false)
        {
            continue;
        }

        if(CheckIsWin(Board,player))
        {
            printf("恭喜|%c|选手获胜\n",player);
            break;
        }
        if(CheckIsDrawn(Board))
        {
            PrintBoard(Board);
            printf("平局\n");
            break;
        }

        player = (player == 'X') ? 'O' : 'X';


    }
    

    return 0;
}